package org.jeese.modules.sys.web;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.jeese.common.bean.ResponseResult;
import org.jeese.common.utils.EncryptUtils;
import org.jeese.common.utils.ShiroUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

/**
 * @Description:登录管理
 * @Package:org.jeese.web.sys
 * @author:wubc
 * @version:1.0
 * @date:2017年10月31日-下午3:25:05
 * @Copyright:2017 Inc. All rights reserved.
 */
@Controller
public class SysLoginController {
	protected Logger log = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private Producer producer;
	
	
	/**
	 * 登录页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "login.html", method = RequestMethod.GET)
	public String login(Model model) {
		if (SecurityUtils.getSubject().isAuthenticated()) {
			return "redirect:index.html";
		}
		return "sys/login/index";
	}
	
	/**
	 * 登录
	 */
	@ResponseBody
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public ResponseResult login(String account, String password, String captcha) throws IOException {
		ResponseResult result = new ResponseResult();
		try {
			Subject subject = ShiroUtils.getSubject();
			if (subject.isAuthenticated()) {
				return result.success();
			}
//			String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
//			if(StringUtils.isEmpty(kaptcha)){
//				return result.error("验证码失效");
//			}
//			if(!captcha.equalsIgnoreCase(kaptcha)){
//				return result.error("验证码不正确");
//			}
			UsernamePasswordToken token = new UsernamePasswordToken(account, password);
			token.setRememberMe(true);
			subject.login(token);
			if (subject.isAuthenticated()) {
		        log.info("User [" + account + "] login in successfully.");
				return result.success();
			} else {
				token.clear();
				return result.error("登录失败");
			}
		} catch (UnknownAccountException e) {
			log.info("对用户[" + account + "]进行登录验证..验证未通过,未知账户");
			return result.error(e.getMessage());
		} catch (IncorrectCredentialsException e) {
			log.info("对用户[" + account + "]进行登录验证..验证未通过,错误的凭证");
			return result.error(e.getMessage());
		} catch (LockedAccountException e) {
			log.info("对用户[" + account + "]进行登录验证..验证未通过,账户已锁定");
			return result.error(e.getMessage());
		} catch (ExcessiveAttemptsException eae) {
			log.info("对用户[" + account + "]进行登录验证..验证未通过,错误次数过多");
			return result.error("用户名或密码错误次数过多");
		} catch (AuthenticationException e) {
			log.info("对用户[" + account + "]进行登录验证..验证未通过,堆栈轨迹如下");
			return result.error("账户验证失败");
		}
	}
	
	
	/**
	 * 退出
	 */
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout() {
		if (SecurityUtils.getSubject().getSession() != null) {
			SecurityUtils.getSubject().logout();
		}
		return "redirect:login.html";
	}
	
	/**
	 * 验证码
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping(value = "captcha", method = RequestMethod.GET)
	public void captcha(HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        //Session session = SecurityUtils.getSubject().getSession();
        SecurityUtils.getSubject().getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
	}
	
	
}
